package com.wh1200.mybatis.xmlless.plugin.visitor

import com.wh1200.mybatis.xmlless.util.TypeUtil
import com.wh1200.mybatis.xmlless.util.getXmllessTableInfo
import net.sf.jsqlparser.schema.Table
import net.sf.jsqlparser.statement.select.FromItemVisitorAdapter
import net.sf.jsqlparser.statement.select.PlainSelect
import net.sf.jsqlparser.statement.select.SubSelect

class FromVisitor : FromItemVisitorAdapter(), BaseSelectVisitor {

  private val tables: MutableMap<String, Class<*>> = mutableMapOf()

  override fun visit(table: Table) {
    val modelClass = TypeUtil.resolve<Any>(table.name)
    val tableInfo = getXmllessTableInfo(modelClass)
    table.name = tableInfo.tableName
    if (table.alias != null) {
      tables[table.alias.name] = modelClass
    }
  }

  override fun visit(subSelect: SubSelect) {
    val selectBody = subSelect.selectBody as PlainSelect
    processSelectBody(selectBody)
  }

  override fun getTables(): MutableMap<String, Class<*>> {
    return tables
  }

}
